﻿using System;
using Domain.Core;
using Domain.MainModule.Entities;
using Domain.MainModule.States;

namespace Application.MainModule.StatesManagement
{
    public class StateManagementService : IStateManagementService, IDisposable
    {
        #region private properties

        private IStateRepository StateRepository
        {
            get;
            set;
        }

        #endregion

        #region constructor

        /// <summary>
        /// Default constructor for CityService.
        /// </summary>
        /// <param name="employeeRepository">StateRepository dependency. Usually this is resolved by IoC</param>
        public StateManagementService(IStateRepository stateRepository)
        {
            if (stateRepository == (IStateRepository)null)
            {
                throw new ArgumentNullException(Resources.Messages.exception_DependenciesAreNotInitialized);
            }

            this.StateRepository = stateRepository;
        }

        #endregion

        #region IStateService implementations

        public void AddState(State state)
        {
            IUnitOfWork unitOfWork = this.StateRepository.UnitOfWork as IUnitOfWork;
            this.StateRepository.Add(state);
            unitOfWork.Commit();
        }

        public void ChangeState(State state)
        {
            IUnitOfWork unitOfWork = this.StateRepository.UnitOfWork as IUnitOfWork;
            this.StateRepository.Modify(state);
            unitOfWork.CommitAndRefreshChanges();
        }

        public State FindStateByName(string stateName)
        {
            StateNameSpecification stateNameSpecification = new StateNameSpecification(stateName);
            return this.StateRepository.FindState(stateNameSpecification);
        }

        #endregion

        #region IDisposable implementation

        public void Dispose()
        {
            if (this.StateRepository != null && this.StateRepository.UnitOfWork != null)
            {
                this.StateRepository.UnitOfWork.Dispose();
            }
        }

        #endregion
    }
}
